package org.cwnuit.train.utils;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class HtmlToDoc {
    /**
     * 读取html文件到word
     * @param filepath html文件的路径
     * @throws Exception
     */
    public boolean writeWordFile(String url) throws Exception {
           boolean flag = false;
           ByteArrayInputStream bais = null;
           FileOutputStream fos = null;
           String path = "D:/";  //根据实际情况写路径
           try {
                  if (!"".equals(path)) {
                         File fileDir = new File(path);
                         if (fileDir.exists()) {
                                String content = getHtmlPage(url);
                                byte b[] = content.getBytes();
                                bais = new ByteArrayInputStream(b);
                                POIFSFileSystem poifs = new POIFSFileSystem();
                                DirectoryEntry directory = poifs.getRoot();
                                @SuppressWarnings("unused")
								DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
                                fos = new FileOutputStream(path + "temp.doc");
                                poifs.writeFilesystem(fos);
                                bais.close();
                                fos.close();
                         }
                  }

           } catch (IOException e) {
                  e.printStackTrace();
           } finally {
                  if(fos != null) fos.close();
                  if(bais != null) bais.close();
           }
           return flag;
    }
    
    public static String getHtmlPage(String url) {
		String result = "";
		try {
			URL httpurl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) httpurl
					.openConnection();
			
			httpConn.setRequestProperty("User-agent","Mozilla/2.0.0.11");
			httpConn.setDoInput(true);

			BufferedReader in = new BufferedReader(new InputStreamReader(
					httpConn.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line + "\n";
			}
			in.close();
		} catch (Exception e) {
			System.out.println("Nothing" + e);
		}
		System.out.println(result);
		return result;
	}
	
	 public static void main(String[] args) throws Exception {
       new HtmlToDoc().writeWordFile("http://www.0817home.com/");
  }

}
